#include<stdio.h>
#include "snake.h"
void initsnake()
{
    //蛇初始化
    snake.size=2;
    snake.head.x=WIDTH/2;
    snake.head.y=HIGHT/2;
    snake.body[0].x=WIDTH/2-1;
    snake.body[0].y=HIGHT/2;
}
void initfood()
{
    //食物初始化
    Food.x=rand()%WIDTH;
    Food.y=rand()%HIGHT;
}

void putsnake()
{
    //修改控制台光标位置
    COORD coord;
    coord.X=snake.head.x;
    coord.Y=snake.head.y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
    //画蛇与食物
    putchar('@');
    for(int i=0;i<snake.size-1;i++)
    {
        coord.X=snake.body[i].x;
        coord.Y=snake.body[i].y;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
        putchar('*');
    }
    //去除蛇尾
    coord.X=lastX;
    coord.Y=lastY;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
    putchar(' ');
    //画食物
    coord.X=Food.x;
    coord.Y=Food.y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
    putchar('#');
    coord.X=WIDTH;
    coord.Y=HIGHT;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void putwall() 
{
    COORD coord;
    // 绘制右侧墙
    for(int i=0; i<HIGHT; i++) {
        coord.X = WIDTH;
        coord.Y = i;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
        putchar('|');
    }
    // 绘制底部墙
    coord.Y = HIGHT;
    for(int j=0; j<=WIDTH; j++) {
        coord.X = j;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
        putchar('_');
    }
}
void playgame()
{
    char key='d';
    //判断蛇撞墙
    while(snake.head.x>=0&&snake.head.x<WIDTH
        &&snake.head.y>=0&&snake.head.y<HIGHT)
        {
            //清屏
            //system("cls"); 
            //接受用户输入
            if(kbhit())
            {
                key=getch();
            }
            if(key==0)
            {
                key=getch();
                switch (key)
                {
                case 59:
                    if(sleepsecond>50)
                    {
                        sleepsecond-=10;
                    }
                    break;
                case 60:
                    if(sleepsecond<500)
                    {
                        sleepsecond+=10;
                    }
                    break;
                case 63:
                    isPaused=!isPaused;
                    coord={0,HIGHT+2};
                    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
                    if(isPaused)
                    {
                        printf("游戏已暂停[按F5继续]");
                    }
                    else
                    {
                        printf("                    ");
                    }
                    break;
                default:
                    break;
                }
            }
            else
            {switch (key)
            {
            case 'w':
                if(ky!=1){
                kx=0;ky=-1;}
                break;
            case 's':
                if(ky!=-1){
                kx=0;ky=1;}
                break;
            case 'a':
                if(kx!=1){
                kx=-1;ky=0;}
                break;
            case 'd':
                if(kx!=-1){
                kx=1;ky=0;}
                break;
            case 27:return;//Esc退出
            default:
                break;
            }}
            if(isPaused)
            {
                Sleep(100);
                continue;
            }
            //蛇撞身体
            for(int i=0;i<snake.size-1;i++)
            {
                if(snake.head.x==snake.body[i].x
                    &&snake.head.y==snake.body[i].y)
                    {
                        return;
                    }
            }
            //蛇吃食物
            if(snake.head.x==Food.x&&snake.head.y==Food.y)
            {
                //食物消失
                initfood();
                //身体增长
                snake.size++;
                //加分
                score+=10;
                //加速
                sleepsecond-=5;
            }
            //蛇移动
            //存储蛇尾坐标
            lastX=snake.body[snake.size-2].x;
            lastY=snake.body[snake.size-2].y;
            for(int i=snake.size-1;i>0;i--)
            {
                snake.body[i].x=snake.body[i-1].x;
                snake.body[i].y=snake.body[i-1].y;
            }
            snake.body[0].x=snake.head.x;
            snake.body[0].y=snake.head.y;
            snake.head.x+=kx;
            snake.head.y+=ky;
            //更新蛇
            putsnake();
            putwall();
            Sleep(sleepsecond); 
        }
    return;
}
void showscore()
{
    COORD coord;
    coord.X=0;
    coord.Y=HIGHT+2;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    printf("Game over!!!\n");
    printf("您的成绩为%d\n",score);
    coord.Y=HIGHT+3;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    printf("按任意键查看排行榜");
    getch();
}
// 加载排行榜
void loadScores() {
    FILE *file = fopen("scores.dat", "rb");
    if (file != NULL) {
        fread(scores, sizeof(int), MAX_SCORES, file);
        fclose(file);
    } else {
        // 初始化空排行榜
        for (int i = 0; i < MAX_SCORES; i++) {
            scores[i] = 0;
        }
    }
}

// 保存排行榜
void saveScores() {
    FILE *file = fopen("scores.dat", "wb");
    if (file != NULL) {
        fwrite(scores, sizeof(int), MAX_SCORES, file);
        fclose(file);
    }
}

// 显示排行榜
void showLeaderboard() {
    system("cls");
    printf("=== 排行榜 ===\n");
    
    // 显示所有记录
    for (int i = 0; i < MAX_SCORES; i++) {
        printf("%2d. %5d\n", i+1, scores[i]);
    }
    
    printf("\n按任意键返回...");
    getch();
}

// 更新排行榜
void addToLeaderboard() {
    // 检查是否能进入排行榜
    if (score > scores[MAX_SCORES-1]) {
        // 放入最后一位并排序
        scores[MAX_SCORES-1] = score;
        for (int i = MAX_SCORES-1; i > 0; i--) {
            if (scores[i] > scores[i-1]) {
                int temp = scores[i];
                scores[i] = scores[i-1];
                scores[i-1] = temp;
            } else {
                break;
            }
        }
        saveScores();
    }
}
int main()
{
    //设置光标不可见
    CONSOLE_CURSOR_INFO cci;
    cci.dwSize=sizeof(cci);
    cci.bVisible=FALSE;
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);
    kbhit();
    //播种随机数
    srand(time(NULL)); 
    initsnake();
    initfood();
    //putsnake();
    playgame();
    showscore();
    loadScores();
    saveScores();
    addToLeaderboard();
    showLeaderboard();
    
    system("pause");
    return 0;
}